package com.gitee.francis.lw.form.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.fasterxml.jackson.databind.JavaType;
import com.gitee.francis.lw.form.model.request.TemplateConfigRequestDTO;
import com.gitee.francis.lw.form.model.response.ControlAllResponseDTO;
import com.gitee.francis.lw.form.model.response.ControlAttrAllResponseDTO;
import com.gitee.francis.lw.form.model.response.FormItemAllResponseDTO;
import com.gitee.francis.lw.form.model.response.TemplateConfigAllResponseDTO;
import com.gitee.francis.lw.form.model.response.TemplateConfigGetResponseDTO;
import com.gitee.francis.lw.form.model.response.TemplateConfigListResponseDTO;
import com.gitee.francis.lw.form.model.search.TemplateConfigSearchDTO;
import com.gitee.francis.lw.form.service.IControlAttrService;
import com.gitee.francis.lw.form.service.IControlService;
import com.gitee.francis.lw.form.service.IFormGroupService;
import com.gitee.francis.lw.form.service.IFormItemService;
import com.gitee.francis.lw.form.service.ITemplateConfigService;
import com.gitee.francis.lw.mapper.FormGroupRItemMapper;
import com.gitee.francis.lw.mapper.TemplateConfigMapper;
import com.gitee.francis.lw.mapper.model.custom.FormGroupRItemCustomDO;
import com.gitee.francis.lw.mapper.model.custom.TemplateConfigCustomDO;
import com.gitee.francis.lw.mapper.model.db.ControlAttrDO;
import com.gitee.francis.lw.mapper.model.db.ControlDO;
import com.gitee.francis.lw.mapper.model.db.FormGroupDO;
import com.gitee.francis.lw.mapper.model.db.FormItemDO;
import com.gitee.francis.lw.mapper.model.db.TemplateConfigDO;
import com.github.pagehelper.PageInfo;
import com.hzlemone.controller.AbstractController;
import com.hzlemone.enums.ResponseStatusEnum;
import com.hzlemone.response.ResponseDTO;
import com.hzlemone.response.ResponsePageDTO;
import com.hzlemone.utils.JsonUtil;

/**
 * @ClassName ElseClassifyController.java
 * @Description 其他分类 REST API
 * @author Francis.LW
 * @date 2018年1月5日
 **/
@RestController
@RequestMapping("/admin/form/template/config")
@Api(value = "表单模板配置 REST API", description = "表单模板配置 REST API")
public class TemplateConfigController
		extends
		AbstractController<TemplateConfigDO, TemplateConfigCustomDO, TemplateConfigSearchDTO, TemplateConfigListResponseDTO, TemplateConfigRequestDTO, TemplateConfigGetResponseDTO> {

	@Autowired
	IControlService controlService;

	@Autowired
	IControlAttrService controlAttrService;

	@Autowired
	ITemplateConfigService templateConfigService;

	@Autowired
	IFormGroupService formGroupService;

	@Autowired
	IFormItemService formItemService;

	@Autowired
	FormGroupRItemMapper formGroupRItemMapper;

	@Autowired
	TemplateConfigMapper templateConfigMapper;

	@ApiOperation(value = "获取表单模板所有配置", notes = "获取表单模板所有配置")
	@RequestMapping(value = "/list/all", method = RequestMethod.POST)
	public ResponseDTO listAll(
			@RequestBody(required = false) TemplateConfigSearchDTO search) {
		ResponseDTO responseDTO = new ResponseDTO();

		try {

			TemplateConfigCustomDO param = new TemplateConfigCustomDO();

			// 设置搜索参数
			if (search != null) {
				param = collectionMapperDecorator.map(search,
						TemplateConfigCustomDO.class);
			}

			List<TemplateConfigCustomDO> templateConfigCustomDOs = templateConfigMapper
					.customSelectByCondition(param);

			templateConfigCustomDOs = templateConfigCustomDOs
					.stream()
					.sorted(Comparator.comparing(
							TemplateConfigCustomDO::getHzLemonEFormItemSort,
							Comparator.nullsLast(Integer::compareTo)))
					.collect(Collectors.toList());

			List<TemplateConfigAllResponseDTO> list = (List<TemplateConfigAllResponseDTO>) collectionMapperDecorator
					.mapCollection(templateConfigCustomDOs,
							TemplateConfigAllResponseDTO.class);

			for (TemplateConfigAllResponseDTO tc : list) {
				List<FormItemAllResponseDTO> formItemAllResponseDTOs = new ArrayList<FormItemAllResponseDTO>();
				if (tc.getHzLemonEIsFormGroup().equals("2")) {
					FormGroupRItemCustomDO formGroupRItemCustomDO = new FormGroupRItemCustomDO();
					formGroupRItemCustomDO.setFormGroupId(tc
							.getFormGroupOrItemId());
					List<FormGroupRItemCustomDO> formGroupRItemCustomDOs = formGroupRItemMapper
							.customSelectByCondition(formGroupRItemCustomDO);
					formGroupRItemCustomDOs = formGroupRItemCustomDOs
							.stream()
							.sorted(Comparator
									.comparing(
											FormGroupRItemCustomDO::getHzLemonEGroupItemSort,
											Comparator
													.nullsLast(Integer::compareTo)))
							.collect(Collectors.toList());
					formItemAllResponseDTOs = (List<FormItemAllResponseDTO>) collectionMapperDecorator
							.mapCollection(formGroupRItemCustomDOs,
									FormItemAllResponseDTO.class);
				}

				if ("d17ca818684f4132a30e3406caa0f963".equals(tc
						.getFormGroupOrItemId())) {
					initGroupItem(tc, formItemAllResponseDTOs,
							"9a8263a882e64d509b8854619e1fa828");
				} else if ("2811e120f64048899596eb97a306afbb".equals(tc
						.getFormGroupOrItemId())) {
					initGroupItem(tc, formItemAllResponseDTOs,
							"272f42b2293040448ba24f0140a1a031");
				} else {
					tc.setFormItems(formItemAllResponseDTOs);
					tc.setValues(new ArrayList<String>());
				}

			}

			responseDTO.setCode(ResponseStatusEnum.SUCCESS.getCode());
			responseDTO.setMessage(ResponseStatusEnum.SUCCESS.getMessage());
			responseDTO.setData(list);

			logger.info("信息列表:" + JsonUtil.toJson(responseDTO));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return responseDTO;
	}

	private void initGroupItem(TemplateConfigAllResponseDTO tc,
			List<FormItemAllResponseDTO> formItemAllResponseDTOs,
			String initItemId) {
		HashMap<String, Object> initItem = new HashMap<String, Object>();

		for (FormItemAllResponseDTO fia : formItemAllResponseDTOs) {
			if (initItemId.equals(fia.getId())) {
				initItem.put("id", fia.getId());
				initItem.put("name", fia.getHzLemonEFormItemName());
				initItem.put("must", 1);
				initItem.put("sort", 1);
				formItemAllResponseDTOs.remove(fia);
				break;
			}
		}
		tc.setFormItems(formItemAllResponseDTOs);
		List<HashMap<String, Object>> initItems = new ArrayList<HashMap<String, Object>>();
		initItems.add(initItem);
		tc.setValues(initItems);
	}

	@ApiOperation(value = "获取表单模板配置列表", notes = "获取表单模板配置列表")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "currentpage", value = "当前页数", defaultValue = "1", paramType = "query", required = true, dataType = "int"),
			@ApiImplicitParam(name = "pagesize", value = "每页记录数", defaultValue = "10", paramType = "query", required = true, dataType = "int") })
	@RequestMapping(value = "/list", method = RequestMethod.POST)
	@Override
	public ResponseDTO list(
			@RequestParam(name = "currentpage", defaultValue = "1") int currentPage,
			@RequestParam(name = "pagesize", defaultValue = "10") int pageSize,
			@RequestBody(required = false) TemplateConfigSearchDTO search) {
		ResponseDTO responseDTO = new ResponseDTO();

		try {
			TemplateConfigCustomDO param = new TemplateConfigCustomDO();

			// 设置搜索参数
			if (search != null) {
				param = collectionMapperDecorator.map(search,
						TemplateConfigCustomDO.class);

				param.setHzLemonEFormGroupCode(search.getCode());
				param.setHzLemonEFormItemCode(search.getCode());
				param.setHzLemonEFormGroupName(search.getName());
				param.setHzLemonEFormItemName(search.getName());
			}
			// 设置分页参数
			param.setPage(currentPage);
			param.setRows(pageSize);

			PageInfo<TemplateConfigCustomDO> pageInfo = service
					.listByPage(param);

			ResponsePageDTO<TemplateConfigListResponseDTO> responsePageDTO = new ResponsePageDTO<TemplateConfigListResponseDTO>();
			List<TemplateConfigListResponseDTO> list = new ArrayList<TemplateConfigListResponseDTO>();
			if (currentPage <= pageInfo.getPages()) {
				list = (List<TemplateConfigListResponseDTO>) collectionMapperDecorator
						.mapCollection(pageInfo.getList(),
								TemplateConfigListResponseDTO.class);
			}

			responsePageDTO.setList(list);
			responsePageDTO.setTotalRecord(pageInfo.getTotal());

			responseDTO.setCode(ResponseStatusEnum.SUCCESS.getCode());
			responseDTO.setMessage(ResponseStatusEnum.SUCCESS.getMessage());
			responseDTO.setData(responsePageDTO);

			logger.info("信息列表:" + JsonUtil.toJson(responseDTO));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return responseDTO;
	}

	@ApiOperation(value = "获取表单模板配置详情", notes = "获取表单模板配置详情")
	@ApiImplicitParam(name = "id", value = "信息id", paramType = "path", required = true, dataType = "String")
	@RequestMapping(value = "/get/{id}", method = RequestMethod.GET)
	@Override
	public ResponseDTO getById(@PathVariable("id") String id) {

		ResponseDTO responseDTO = new ResponseDTO();
		TemplateConfigGetResponseDTO templateConfigGetResponseDTO = new TemplateConfigGetResponseDTO();
		TemplateConfigDO templateConfigDO = templateConfigService.getById(id);

		templateConfigGetResponseDTO.setFormItemType(templateConfigDO
				.getHzLemonEIsFormGroup());
		templateConfigGetResponseDTO.setItemSort(templateConfigDO
				.getHzLemonEFormItemSort());

		switch (templateConfigDO.getHzLemonEIsFormGroup()) {
		case "1":
			FormItemDO formItemDO = formItemService.getById(templateConfigDO
					.getFormGroupOrItemId());
			templateConfigGetResponseDTO = collectionMapperDecorator.map(
					formItemDO, TemplateConfigGetResponseDTO.class);
			templateConfigGetResponseDTO.setFormItemType(templateConfigDO
					.getHzLemonEIsFormGroup());
			templateConfigGetResponseDTO.setItemSort(templateConfigDO
					.getHzLemonEFormItemSort());
			List<ControlAllResponseDTO> controlAllResponseDTOs = new ArrayList<ControlAllResponseDTO>();
			HashMap<String, Object> param = new HashMap<String, Object>();

			List<ControlDO> controlDOs = controlService.listBy(param);

			for (ControlDO control : controlDOs) {
				ControlAllResponseDTO controlAllResponseDTO = collectionMapperDecorator
						.map(control, ControlAllResponseDTO.class);

				List<ControlAttrAllResponseDTO> controlAttrAllResponseDTOs = new ArrayList<ControlAttrAllResponseDTO>();
				HashMap<String, Object> attrParam = new HashMap<String, Object>();
				attrParam.put("controlId", control.getId());
				List<ControlAttrDO> controlAttrDOs = controlAttrService
						.listBy(attrParam);
				if (controlAttrDOs != null && controlAttrDOs.size() != 0) {
					controlAttrAllResponseDTOs = (List<ControlAttrAllResponseDTO>) collectionMapperDecorator
							.mapCollection(controlAttrDOs,
									ControlAttrAllResponseDTO.class);

					for (ControlAttrAllResponseDTO caa : controlAttrAllResponseDTOs) {
						caa.setValue(getAttrValue(
								formItemDO.getHzLemonEFormItemAttr(),
								caa.getHzLemonEControlAttrCode()));
					}
				}
				controlAllResponseDTO.setAttr(controlAttrAllResponseDTOs);
				controlAllResponseDTOs.add(controlAllResponseDTO);
			}
			templateConfigGetResponseDTO
					.setControlAllResponseDTOs(controlAllResponseDTOs);
			break;
		case "2":
			FormGroupDO formGroupDO = formGroupService.getById(templateConfigDO
					.getFormGroupOrItemId());
			templateConfigGetResponseDTO
					.setHzLemonEFormItemCode(templateConfigDO
							.getFormGroupOrItemId());
			templateConfigGetResponseDTO.setHzLemonEFormItemName(formGroupDO
					.getHzLemonEFormGroupName());
			break;
		default:
			break;
		}
		responseDTO.setCode(ResponseStatusEnum.SUCCESS.getCode());
		responseDTO.setMessage(ResponseStatusEnum.SUCCESS.getMessage());
		responseDTO.setData(templateConfigGetResponseDTO);
		return responseDTO;
	}

	private Object getAttrValue(String itemAttr, String key) {
		JavaType javaType = JsonUtil.getCollectionType(ArrayList.class,
				HashMap.class);
		List<HashMap<String, Object>> attrList = JsonUtil.fromJson(itemAttr,
				javaType);

		for (HashMap<String, Object> attr : attrList) {
			if (attr.get("key").equals(key)) {
				return attr.get("value");
			}
		}

		return null;
	}

	@ApiOperation(value = "删除表单模板配置", notes = "删除表单模板配置，可进行单条或批量删除")
	@RequestMapping(value = "/delete", method = RequestMethod.POST)
	@Override
	public ResponseDTO remove(@RequestBody String[] ids) {
		return super.remove(ids);
	}
}
